﻿using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Http.Headers;
using Traceability.Doamin;
using Traceability.ErrorCode;
using Traceability.Infratruvture.Interfares;
using Traceability.Read.Api.Application.Command;
using Traceability.Read.Api.Dto;

namespace Traceability.Read.Api.Application.CommandHander
{
    public class LoginHander : IRequestHandler<LoginCommand, ApiResult<LoginDto>>
    {

        private readonly IMapper mapper;
        private readonly IBaseRequsitory<User> baseRequsitory;

        public LoginHander(IMapper mapper, IBaseRequsitory<User> baseRequsitory)
        {
            this.mapper = mapper;
            this.baseRequsitory = baseRequsitory;
        }

        /// <summary>
        /// 登录方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<LoginDto>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            ApiResult<LoginDto> result = new ApiResult<LoginDto>();

            var list = baseRequsitory.GetAll().Where(x => x.UserName == request.UserName).FirstOrDefault();

            if (list == null)
            {
                result.Code = ApiEnum.用户名不存在;
                result.Msg = ApiEnum.用户名不存在.ToString();
            }
            else
            {
                if (list.Password != request.Password)
                {
                    result.Code = ApiEnum.密码错误;
                    result.Msg = ApiEnum.密码错误.ToString();
                }
                else
                {
                    result.Code = ApiEnum.登录成功;
                    result.Msg = ApiEnum.登录成功.ToString();
                    result.Data = mapper.Map<LoginDto>(list);
                }
            }

            return Task.FromResult(result);
        }
    }
}
